package com.tongsys.server.config.security.service;

import com.tongsys.server.config.redis.RedisService;
import com.tongsys.server.config.redis.RedisUtils;
import com.tongsys.server.entity.Permission;
import com.tongsys.server.entity.User;
import com.tongsys.server.service.IPermissionService;
import com.tongsys.server.service.IUserService;
import io.swagger.annotations.ApiModel;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;


@Component //注入IOC 容器
@ApiModel("创建类 实现 UserDetailsService 接口，并将得到的用户数据 封装到 UserDetails 的实现类中 并返回 ")
public class MyUserDetailsService implements UserDetailsService {
    @Resource
    private IUserService iUserService;
    @Resource
    private IPermissionService iPermissionService;
    @Autowired
    private RedisService redisService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        //根据名称查找 登录用户
        User user = iUserService.findUserByUserName(username);
        //不存在该用户
        if (user==null){
            throw new UsernameNotFoundException("用户名或密码错误");
        }

        //TODO 存在用户，获取用户权限
        //存在用户，获取用户权限
        List<Permission> permissions = iPermissionService.findPermissionByUserId(user.getId());
        System.out.println(permissions);
        //获取对应的权限编码
        List<String> list = permissions.stream().filter(item -> item != null).map(item -> item.getCode()).distinct().collect(Collectors.toList());

        //设置用户拥有的菜单信息
        user.setPermissionList(list);

        //返回实现了 UserDetails 的对象
        return user;
    }
}
